package com.gw2.gw2world.fragment;

import java.util.Collections;

import android.app.Fragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.gw2.gw2world.R;
import com.gw2.gw2world.controller.DatabaseOpenHelper;
import com.gw2.gw2world.controller.EventDownloader;
import com.gw2.gw2world.controller.OnTaskCompleted;
import com.gw2.gw2world.controller.Tools;
import com.gw2.gw2world.model.Event;
import com.gw2.gw2world.model.ServerState;

public class TempleDungeonFragment extends Fragment implements OnTaskCompleted, OnGroupClickListener {
	//@SuppressWarnings("unused")
	private static final String TAG="TempleDungeonFragment";
	private static final long REFRESH_RATE=30000;
	private DatabaseOpenHelper dbHelper;
	protected SQLiteDatabase db;
	protected Cursor c;
	private SharedPreferences  prefs;
	private SparseArray<ServerState> ss_mapping=new SparseArray<ServerState>(52);
	private Handler  handler=new Handler();
	private Runnable task;
	private EventDownloader downloader;
	private ExpandableListView elv_servers;
	private ProgressBar pb_refreshing;
	private BasicExpandableEventAdapter adapter;
	private int map_id=0;
	private int master=0;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		Tools.forceLocale(getActivity());
		View v=inflater.inflate(R.layout.temple_dungeon_detail, null);
		map_id=getActivity().getIntent().getExtras().getInt("map_id");
		TextView tv_event=(TextView)v.findViewById(R.id.tv_td_event_name);
		tv_event.setText(getActivity().getIntent().getExtras().getInt("event_name"));
		switch (getActivity().getIntent().getExtras().getInt("event_name")) {
		case R.string.event_temple_of_balthazar:
			master = 18;
			break;
		case R.string.event_temple_of_dwayna:
			master = 19;
			break;
		case R.string.event_temple_of_lyssa:
			master = 20;
			break;
		case R.string.event_temple_of_melandru:
			master = 21;
			break;
		case R.string.event_temple_of_grenth:
			master = 22;
			break;
		case R.string.dungeon_arah:
			master = 17;
			break;
		case R.string.dungeon_cof:
			master = 23;
			break;
		case R.string.dungeon_coe:
			master = 24;
			break;
		default:
			break;
		}
		tv_event.setCompoundDrawablesWithIntrinsicBounds(getActivity().getIntent().getExtras().getInt("event_drawable"), 0, 0, 0);
		((TextView)v.findViewById(R.id.tv_td_map)).setText(getActivity().getIntent().getExtras().getString("map_name",""));
		pb_refreshing=(ProgressBar)v.findViewById(R.id.pb_td);
		//adapter=new BasicEventAdapter(getActivity(), states);
		/*lv_servers=(ListView)v.findViewById(R.id.lv_td);
		lv_servers.setOnItemClickListener(this);*/
		elv_servers=(ExpandableListView)v.findViewById(R.id.elv_td);
		prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
		dbHelper = new DatabaseOpenHelper(getActivity(), "database", null, 1);
		//dbHelper.insertWorldEvents();
		db = dbHelper.getReadableDatabase();
		//get the server list
		c = db.query("server", null, "lang=? AND id"+String.valueOf(prefs.getInt("home_server", 0)<2000?"<2000":">1999"), new String[] { prefs.getString("language", "en") }, null,null,null);
		while (c.moveToNext()) {
			ServerState ss=new ServerState();
			ss.server_id=c.getInt(0);
			ss.name=c.getString(2);
			ss.state=getResources().getString(R.string.state_closed);
			ss_mapping.put(ss.server_id, ss);
			//adapter.add(ss);
		}
		adapter=new BasicExpandableEventAdapter();
		elv_servers.setAdapter(adapter);
		//elv_servers.setOnGroupClickListener(this);
		db.close();
		start();
		return v;
	}
	@Override
	public void onPause() {
		if(downloader!=null) downloader.cancel(true);
		handler.removeCallbacksAndMessages(null);
		Tools.unlockScreen(getActivity());
		super.onPause();
	}
	@Override
	public void onResume() {
		Tools.lockScreenFromPreferences(getActivity());
		if(downloader!=null && task!=null) start();
		super.onResume();
	}

	private void start() {
		handler.removeCallbacksAndMessages(null);
		downloader=new EventDownloader(getActivity(), prefs.getString("language", "en"),prefs.getInt("home_server", 0),prefs.getInt("guest1_server", 0),prefs.getInt("guest2_server", 0), true);
		downloader.setWorkingView(pb_refreshing);
		downloader.setMap(map_id);
		downloader.setAllServers(true);
		downloader.setOnTaskCompletedListener(this);
		downloader.execute();
	}
	@Override
	public void onTaskCompleted() {
		ServerState ss=null;
		for(int i=0; i<ss_mapping.size(); i++) {
			ss=ss_mapping.valueAt(i);
			ss.events.clear();
			ss.state=getResources().getString(R.string.state_closed);
			for(Event e : downloader.getServerEvents(ss.server_id))
				if(e.master==master) {
					ss.events.add(e);
					char state=ss.getState();
					if(state==ServerState.STATE_ATTACKING)
						ss.state=getResources().getString(R.string.state_attacking);
					else if(state==ServerState.STATE_DEFENDING)
						ss.state=getResources().getString(R.string.state_defending);
					else if(state==ServerState.STATE_OPEN)
						ss.state=getResources().getString(R.string.state_open);
					else if(state==ServerState.STATE_CLOSED)
						ss.state=getResources().getString(R.string.state_closed);
				}
			Collections.sort(ss.events, Event.SORT_BY_DEPTH);
			//android.util.Log.d(TAG, "server "+ss_mapping.valueAt(i).server_id+", events : " + ss_mapping.valueAt(i).events.size());
		}
		adapter.notifyDataSetChanged();
		android.util.Log.d(TAG, "Event retrieved : " + String.valueOf(downloader.getEvents().size()));
		task = new Runnable() {
			@Override
			public void run() {start();}
		};
		handler.postDelayed(task, REFRESH_RATE);
	}
	public class BasicExpandableEventAdapter extends BaseExpandableListAdapter {
		@Override
		public Object getChild(int groupPosition, int childPosition) {
			return ss_mapping.get(ss_mapping.keyAt(groupPosition)).events.get(childPosition);
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			return 0;
		}

		@Override
		public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
			LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflater.inflate(R.layout.temple_dungeon_line_detail, parent, false);
			TextView tv_name=(TextView) convertView.findViewById(R.id.tv_td_line_detail_event);
			tv_name.setText(ss_mapping.valueAt(groupPosition).events.get(childPosition).name);
			TextView tv_state=(TextView) convertView.findViewById(R.id.tv_td_line_detail_state);
			tv_state.setText(ss_mapping.valueAt(groupPosition).events.get(childPosition).state);
			if(ss_mapping.valueAt(groupPosition).getState()==ServerState.STATE_OPEN) tv_state.setTypeface(null, Typeface.BOLD);
			else tv_state.setTypeface(null, Typeface.NORMAL);
			return convertView;
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			return ss_mapping.get(ss_mapping.keyAt(groupPosition)).events.size();
		}

		@Override
		public Object getGroup(int groupPosition) {
			return ss_mapping.get(ss_mapping.keyAt(groupPosition));
		}

		@Override
		public int getGroupCount() {
			return ss_mapping.size();
		}

		@Override
		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		@Override
		public View getGroupView(int position, boolean isExpanded, View convertView, ViewGroup parent) {
			LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflater.inflate(R.layout.temple_dungeon_line, parent, false);
			TextView tv_name = (TextView)convertView.findViewById(R.id.tv_td_server);
			TextView tv_state= (TextView)convertView.findViewById(R.id.tv_td_state);
			tv_name .setText(ss_mapping.valueAt(position).name);
			if(ss_mapping.valueAt(position).server_id==prefs.getInt("home_server", 0))
				tv_name.setCompoundDrawablesWithIntrinsicBounds(R.drawable.home, 0, 0, 0);
			else if(ss_mapping.valueAt(position).server_id==prefs.getInt("guest1_server", 0) || ss_mapping.valueAt(position).server_id==prefs.getInt("guest2_server", 0))
				tv_name.setCompoundDrawablesWithIntrinsicBounds(R.drawable.guest, 0, 0, 0);
			tv_state.setText(ss_mapping.valueAt(position).state);
			if(ss_mapping.valueAt(position).state.equals(getResources().getString(R.string.state_open)))
				tv_state.setTextColor(getResources().getColor(R.color.event_success));
			else if(ss_mapping.valueAt(position).state.equals(getResources().getString(R.string.state_closed)))
				tv_state.setTextColor(getResources().getColor(R.color.event_fail));
			else if(ss_mapping.valueAt(position).state.equals(getResources().getString(R.string.state_attacking)))
				tv_state.setTextColor(getResources().getColor(R.color.event_active));
			else if(ss_mapping.valueAt(position).state.equals(getResources().getString(R.string.state_defending)))
				tv_state.setTextColor(getResources().getColor(R.color.event_active));
			return convertView;
		}

		@Override
		public boolean hasStableIds() {return true;}
		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {return true;}
		
	}
	@Override
	public boolean onGroupClick(ExpandableListView parent, View v, int position, long id) {
		android.util.Log.d(TAG,"Group clicked at " + position);
		parent.smoothScrollToPosition(position);
		if(parent.isGroupExpanded(position)) parent.expandGroup(position);
		else parent.collapseGroup(position);
		return true;
	}
}
